// 登录。根据用户账户+密码+身份，获取用户信息和加入的班级信息
import express from 'express';
import pool from "../importantApi/db_connection.js";

const router = express.Router();
router.post('/', async (req, res) => {
    const {account, name, password, identity} = req.body;
    if (!account || !name || !password || !identity) {
        return res.status(401).json({
            code: 401,
            msg: "缺少注册信息"
        });
    }
    let date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    let createTime = `${year}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')} ${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`
    try {
        // 先检测注册账户是否被注册
        let [result] = await pool.query(`
            select count(*) as count
            from userinfo
            where account = '${account}'
        `)
        if (result[0].count > 0) {
            return res.status(201).json({
                code: 201,
                msg: "该账户已被注册"
            })
        }
        let sql = `
            insert into userinfo (user_name, account, password, identity, createtime)
            values ('${name}', '${account}', '${password}', '${identity}', '${createTime}')
        `
        let [result2] = await pool.query(sql);
        if (result2.affectedRows > 0) {
            return res.status(200).json({
                code: 200,
                msg: "注册成功",
                data: {
                    user_id: result2.insertId,
                    user_name: name,
                    createtime: createTime,
                    identity,
                    hasJoinClass: 0
                }
            })
        } else {
            res.status(201).json({
                code: 201,
                msg: "注册失败"
            })
        }
    } catch (err) {
        return res.status(500).json({
            code: 500,
            error: err,
            msg: "注册错误：server error"
        })
    }
})
export default router;